#include "slist.h"

SLTNode* BuyListNode(int x)               //创建一个新节点
{
	
	SLTNode* newnode = (SLTNode*)malloc(sizeof(SLTNode));
	assert(newnode);
	newnode->date = x;
	newnode->next = NULL;
	return newnode;
}

void SListPushFront(SLTNode** pphead, int x)  //头插法
{
	SLTNode* newnode = BuyListNode(x);
	newnode->next = *pphead;
	*pphead = newnode;
}

void SListpushback(SLTNode** pphead,int x)
{
	SLTNode* newnode = BuyListNode(x);
	newnode->next = NULL;
	if (*pphead == NULL)
		*pphead = newnode;
	else
	{    //找到尾结点
		SLTNode* tail = *pphead;
		while (tail->next)
		{
			tail = tail->next;
		}
		tail->next = newnode;
	}
}

void SListprint(SLTNode* phead)     //打印链表
{
	SLTNode* cail = phead;
	while (cail != NULL)
	{
		printf("%d -> ", cail->date);
		cail = cail->next;
	}
	printf("\n");
}

void SlistpopBack(SLTNode ** pphead)
{
	if (*pphead == NULL)			//没有节点的情况
		return;
	if ((*pphead)->next == NULL)	//一个节点的情况
	{
		free(*pphead);
		*pphead = NULL;
	}
	else							//两个节点以上的情况
	{
		SLTNode* tail = *pphead;
		while(tail->next->next)
		{
			tail = tail->next;
		}
		free(tail->next);
		tail->next = NULL;
	}
}

void SListPopFront(SLTNode** pphead)    //头删法
{
	//if (*pphead == NULL)
	//	return;
	//else
	//{
	//	SLTNode* cail = *pphead;   //释放第一个节点
	//	*pphead = (*pphead)->next;
	//	free(cail);
	//}
	assert(*pphead != NULL);

	SLTNode* tail = (*pphead)->next;
	free(*pphead);
	*pphead = tail;
}

SLTNode* SLTistFind(SLTNode* phead, int x)          //寻找值为x的节点
{
	SLTNode* cur = phead;
	while (cur)
	{
		if (cur->date == x)
		{
			return cur;
		}
		else
		{
			cur = cur->next;
		}
	}	
	return NULL;
}

void sltist_insert(SLTNode** pphead, SLTNode* pos, int x)  //在pos前插入节点
{
	SLTNode* newnode = BuyListNode(x);
	//找到pos前一个结点
	if (*pphead == pos)  //当要找的节点pos为头节点
	{
		newnode->next = *pphead;
		*pphead = newnode;
	}
	else
	{
		SLTNode* pev = *pphead;
		while (pev->next != pos)
		{
			pev = pev->next;
		}
		pev->next = newnode;
		newnode->next = pos;
	}
}

void sltist_insert_after(SLTNode** pphead, SLTNode* pos, int x)  //在pos后插入节点
{
	SLTNode* newnode = BuyListNode(x);
	newnode->next = pos->next;
	pos->next = newnode;
}

void SListEraes(SLTNode** pphead,SLTNode* pos)			//删除当前节点
{
	SLTNode* pev = *pphead;
	//当删除的节点是头节点
	if (pos == *pphead)
	{
		*pphead = pos->next;
		free(pos);
	}
	else
	{
		while (pev->next != pos)
		{
			pev = pev->next;
		}
		pev->next = pos->next;
		free(pos);
	}
}